package com.etrans.web.gps.business.report.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.mail.Flags.Flag;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.etrans.web.gps.base.service.BaseService;
import com.etrans.web.gps.business.alarm.service.AlarmService;
import com.etrans.web.gps.business.report.domain.StaticcalAnomalVo;
import com.etrans.web.gps.business.system.domain.VehicleVo;
import com.etrans.web.gps.business.system.service.VehicleService;
import com.etrans.web.gps.common.MGTemplete;

@Service
public class StatisticalAnomalyService extends BaseService{

	private static String tableNamePrefix = "alarm_info_adas_";
	
	@Autowired
	private AlarmService alarmService;
	
	@Autowired
	private VehicleService vehicleService;
	
	List<HashMap<String, Object>> pieResult = null;
	List<HashMap<String, Object>> charResult = null;
	
	/**
	 * 
	 * @param whereMap 查询条件
	 * @param times  查询次数，因为如果日期是多天的，这时我们需要查询多次
	 * @return
	 */
	public List<HashMap<String, Object>> queryDieDataMap(HashMap<String, Object> whereMap,int  tableNameSuffix,int times) {
		pieResult = new ArrayList<HashMap<String, Object>>();
		//由于表是按天的，所以应该判断多少天，然后每天查一次
		for (int i = 0; i <= times; i++) {
			String tableName = tableNamePrefix +  tableNameSuffix;
			List<Object> result = MGTemplete.groupBy("egov", tableName, whereMap,"alarm_type",null,0);
			//解析
			analysisPie(result);
			tableNameSuffix = tableNameSuffix + 1;
		}
			 
		return pieResult;
 
	}
	
	/**
	 * 
	 * @param list
	 * 
	 * @return
	 */
	private List<HashMap<String, Object>> analysisPie(List<Object> list){
		for (Object obj : list) {
			String jsonStr = JSONObject.toJSONString(obj);
			JSONObject json = JSON.parseObject(jsonStr);
			int alarmType =  (int) json.get("_id");
			int count = (int)json.get("count");
			//查询相应的报警类型
			String name = alarmService.queryAlarmTypeById(alarmType);
			
			//判断pieResult是否存在相对应的报警，如果有 应当count相加
			boolean flag = false;
			for (HashMap<String, Object> h:pieResult) {
				if (alarmType == (Integer)h.get("id")) {
					h.put("value", (int)h.get("value") + count);
					flag = true;
					break;
				}
			}
			//如果没有存在，则添加到数组中
			if (!flag) {
				HashMap<String, Object> hashMap = new HashMap<>();
				hashMap.put("id", alarmType);
				hashMap.put("name", name);
				hashMap.put("value", count);
				pieResult.add(hashMap);
			}
	
		}
		return pieResult;
	}
    
	public Map<String, Object> getChartData(HashMap<String, Object> whereMap,int  tableNameSuffix,int times) {	
		Map<String, Object> maps = new HashMap<>();
		charResult = new ArrayList<HashMap<String,Object>>();
		List<String> xAixs = new ArrayList<>();
		List<Integer> yAixs = new ArrayList<>();
		List<Integer> vehicleIds = new ArrayList<>();
		//根据车牌号码分组
		//由于表是按天的，所以应该判断多少天，然后每天查一次
		for (int i = 0; i <= times; i++) {
			String tableName = tableNamePrefix +  tableNameSuffix;
			List<Object> result = MGTemplete.groupBy("egov", tableName, whereMap,"vehicle_no",null,0);
			if (result != null || result.size() > 0) {
				//解析
				analysisChart(result);
			}
			
			tableNameSuffix = tableNameSuffix + 1;
		}
		//List<Integer> alarmKindId = new ArrayList<>();
		if (charResult == null || charResult.size() == 0 ) {
			yAixs.add(0);
			xAixs.add("");
		}else {
			for (HashMap<String, Object> hashMap : charResult) {
				xAixs.add((String)hashMap.get("vehicleNo"));
				yAixs.add((int)hashMap.get("count"));
				vehicleIds.add((int)hashMap.get("vehicleId"));
			//	alarmKindId.add((int)hashMap.get("alarmkind_id"));
			}
		
		}
		maps.put("xAixs", xAixs);
		maps.put("yAxis", yAixs);
		maps.put("vehicleIds", vehicleIds);
		//maps.put("alarmKindIds",alarmKindId);
 		return maps;	
	}
	private List<HashMap<String, Object>> analysisChart(List<Object> list){
		for (Object obj : list) {
			String jsonStr = JSONObject.toJSONString(obj);
			JSONObject json = JSON.parseObject(jsonStr);
			String verhicleNo=  (String) json.get("_id");
			int count = (int)json.get("count");
			//查询相应的报警类型
			HashMap<String, Object> params = new HashMap<>();
			params.put("vehicleNo", verhicleNo);
			int vehicleId   = vehicleService.queryVehicleIdByVehicleNo(params);
						
			//判断CharResult是否存在相对应的车辆，如果有 应当count相加
			boolean flag = false;
			for (HashMap<String, Object> h:charResult) {
				if (verhicleNo.equals((String)h.get("vehicleNo"))) {
					h.put("count", (int)h.get("count") + count);
					flag = true;
					break;
				}
			}
			//如果没有存在，则添加到数组中
			if (!flag) {
				HashMap<String, Object> hashMap = new HashMap<>();
				hashMap.put("vehicleId", vehicleId);
				hashMap.put("vehicleNo", verhicleNo);
				hashMap.put("count", count);
				charResult.add(hashMap);
			}
	
		}
		return charResult;
	}
	
	@SuppressWarnings("null")
	public List<StaticcalAnomalVo> queryAnomalyList(HashMap<String, Object> whereMap,int  tableNameSuffix,int times) {
		List<StaticcalAnomalVo> list = new ArrayList<>();
		for (int i = 0; i <= times; i++) {
		   String tableName = tableNamePrefix + tableNameSuffix;
		   List<StaticcalAnomalVo> staticcalAnomalVos = MGTemplete.find("egov", tableName, whereMap,StaticcalAnomalVo.class,true);
		   if (staticcalAnomalVos != null || staticcalAnomalVos.size() > 0) {
	 	      list.addAll(staticcalAnomalVos);	
	     	}
		   tableNameSuffix ++;
		}
		return list;
	}
	
	/**
	 * 查询报警图片
	 * 
	 * @param vehicleId
	 * @param id
	 * @param startTime
	 * @param endTime
	 * @return
	 */
	public Map<String, Object> queryPictureListByTime(String vehicleNo, String alarmTime) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
//		try {
//			Map<String, Object> whereMap = new HashMap<String, Object>();
//			whereMap.put("vehicle_no", vehicleNo);
//			whereMap.put("gps_time", alarmTime);
//			//paramMap.put("tableName", "sys_image_" + alarmTime.substring(0, 7).replace("-", "_"));
//			List<PictureVO> barList = selectList("PictureQuery.queryPictureListByTime", paramMap);
//			if (barList != null && barList.size() > 0) {
//				String imgUrl = "";int media_format = 0;
//				for (PictureVO vo : barList) {
//					imgUrl = vo.getExtension();
//					if (imgUrl == null || imgUrl == "") {
//						imgUrl = Utils.formatImageFilename(vo.getTerminalID(), vo.getCameraNo(), vo.getGpsTime());
//						media_format = vo.getMediaFormat();
//					}else {
//						long diffTime =  Math.abs(vo.getGpsTime().getTime()-(DateUtil.getStrToDateFormat(alarmTime, "yyyy-MM-dd HH:mm:ss")).getTime());
//						if (diffTime < 1000) {
//							imgUrl = Utils.formatImageFilename(vo.getTerminalID(), vo.getCameraNo(), vo.getGpsTime());
//							media_format = vo.getMediaFormat();
//						}
//					}
//				}
//				if (media_format == 5) {
//					imgUrl = imgUrl.replaceAll(".jpg", ".mp4");
//				}
//				resultMap.put("imgUrl", config.imagePath + imgUrl);
//				resultMap.put("mediaFormat", media_format);
//				resultMap.put("isHave", 1);
//			}else {
//				resultMap.put("imgUrl", "");
//				resultMap.put("isHave", 0);
//			}
//		} catch (ParseException e) {
//			e.printStackTrace();
//		}
		return resultMap;
	}
	
}
